package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {//id是jwt里面的
        //将图片上传阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2,调用百度云是否包含人脸（目前报bug所以就不用了）
        //如果不包含人脸，就抛出异常
        //包含人脸，调用api更新
        UserInfo userInfo =new UserInfo();
        userInfo.setId(Long.valueOf(id));
        userInfo.setAvatar(imageUrl);
        userInfoApi.update(userInfo);
    }

    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo userInfoVo =new UserInfoVo();
        if(userInfo!=null) {
            BeanUtils.copyProperties(userInfo, userInfoVo);
        }
        if(userInfo.getAge()!=null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        User byId = userApi.findById(userID);
        if(byId.getHxUser()==null){
            //如果为空就创建环形
            String hxUser ="hx"+byId.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create){
                byId.setHxUser(hxUser);
                byId.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(byId);
            }
        }
        return userInfoVo;
    }
    //跟新
    public void update(UserInfo userInfo) {
         userInfoApi.update(userInfo);
    }
}
